package lsl.leetCode.year2023.test0126;


/**
 * 121.卖出股票的最佳时机
 */
public class test121 {
    public static void main(String[] args) {
        int[] nums = {2, 5, 1, 3};
        System.out.println(maxProfit(nums));
    }

    //动态规划:一次遍历
    public static int maxProfit(int[] prices) {
        //用一个变量minProfit记录一个历史最低价格
        int minProfit = Integer.MAX_VALUE;
        //在第i天卖出股票能得到的利润就是prices[i] - minProfit
        int maxProfit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minProfit) {
                minProfit = prices[i];
            }
            if (prices[i] - minProfit > maxProfit) {
                maxProfit = prices[i] - minProfit;
            }
        }
        return maxProfit;
    }
}
